﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using WebAPI中介者模式示例MediatR_EFCroe_Thransaction.DAL;
using WebAPI中介者模式示例MediatR_EFCroe_Thransaction.Event;

namespace WebAPI中介者模式示例MediatR_EFCroe_Thransaction.Handler
{
    // 库存处理程序（减少库存）
    public class InventoryHandler : INotificationHandler<OrderCreatedEvent>
    {
        private readonly AppDbContext _dbContext;

        public InventoryHandler(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task Handle(OrderCreatedEvent notification, CancellationToken cancellationToken)
        {
            // 更新库存
            var product = await _dbContext.Products
                .FirstAsync(p => p.Id == notification.ProductId, cancellationToken);

            product.StockQuantity -= notification.Quantity;
            await _dbContext.SaveChangesAsync(cancellationToken);

            Console.WriteLine($"库存已更新 - 产品ID: {notification.ProductId}, 剩余库存: {product.StockQuantity}");
        }
    }

}
